package wicresoft.controller.jianYan;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import services.business.BusinessInfoServices;
import services.business.BusinessMajorServices;
import services.dictionary.CertificateTypeServices;
import services.dictionary.MajorTypeServices;
import services.expertInfo.ExpertBaseServices;
import services.expertInfo.ExpertCertificateServices;
import services.expertInfo.ExpertCompanyServices;
import util.JsonUtil;
import util.key.IDFactory;
import wicresoft.controller.common.CommonResult;
import wicresoft.controller.common.Properties;
import wicresoft.controller.common.UserIdHandle;
import wicresoft.orm.entity.JyCheckPlan;
import wicresoft.orm.entity.JyExpertGroup;
import wicresoft.orm.entity.UnitUser;
import wicresoft.services.expertInfo.UnitUserServices;
import wicresoft.services.jianYan.JyCheckPlanServices;
import wicresoft.services.jianYan.JyExpertGroupServices;
import wt.entity.business.BusinessInfo;
import wt.entity.business.BusinessMajor;
import wt.entity.dictionary.MajorType;
import wt.entity.expertInfo.ExpertBase;
import wt.entity.expertInfo.ExpertCertificate;
import wt.entity.expertInfo.ExpertCompany;
import wt.staticData.ShortData;
import wt.webPlugin.ZTree;

import java.util.*;

/**
 * Created by Administrator on 2018/3/12.
 */
@Controller
@RequestMapping("httpPage")
public class JianYanExtractionExpertController {
    @Autowired
    JyCheckPlanServices jyCheckPlanServices;
    @Autowired
    JyExpertGroupServices jyExpertGroupServices;
    @Autowired
    UserIdHandle userIdHandle;
    @Autowired
    BusinessInfoServices businessInfoServices;
    @Autowired
    ExpertBaseServices expertBaseServices;
    @Autowired
    ExpertCertificateServices expertCertificateServices;
    @Autowired
    CertificateTypeServices certificateTypeServices;
    @Autowired
    ExpertCompanyServices expertCompanyServices;

    @Autowired
    UnitUserServices unitUserServices;

    @Autowired
    MajorTypeServices majorTypeServices;
    @Autowired
    BusinessMajorServices businessMajorServices;

    @RequestMapping(value = "extractExpertPage")
    public String extractExpertPage(String businessCode, String checkPlanId, Map map) throws Exception {

        if (StringUtils.isBlank(businessCode)) {
            JyCheckPlan jyCheckPlan = jyCheckPlanServices.selectById(checkPlanId);
            businessCode = jyCheckPlan.getAcceptedId();

        }

        List<JyExpertGroup> jyExpertGroupList = jyExpertGroupServices.selectByApplyId(checkPlanId);
        if (!jyExpertGroupList.isEmpty()) {//微创库已经有专家
            List<String> idList = new ArrayList<String>();
            String leaderIdCard = null;
            for (JyExpertGroup jyExpertGroup : jyExpertGroupList) {
                idList.add(jyExpertGroup.getIdCard());
                if ("ybdd_common_dic_export_dute_01".equals(jyExpertGroup.getDuty())) {//获取组长
                    leaderIdCard = jyExpertGroup.getIdCard();
                }
            }

            List<ExpertBase> expertInfoList = expertBaseServices.selectByIdCard(idList);
            List<String> expertBaseIdList = new ArrayList<String>();
            for (ExpertBase expertBase : expertInfoList) {
                expertBaseIdList.add(expertBase.getId());
            }

            JSONArray jsonArray = new JSONArray();
            for (ExpertBase expertBase : expertInfoList) {

                JSONObject jsonObject = new JSONObject();
                jsonObject.put("name", expertBase.getName());
                jsonObject.put("idCard", expertBase.getIdCard());
                jsonObject.put("sex", expertBase.getSex());
                jsonObject.put("phone", expertBase.getPhone());
                jsonObject.put("id", expertBase.getId());
                jsonObject.put("email", expertBase.getEmail());

                ExpertCompany expertCompany = expertCompanyServices.adminSelectByExpertIdOnly(expertBase.getId());
                if (expertCompany != null) {
                    jsonObject.put("affiliateCompany", expertCompany.getAffiliate());
                }


                ExpertCertificate expertCertificate = expertCertificateServices.adminSelect(expertBase.getId(), Properties.JY_ITEM_ID);

                if (expertCertificate != null) {
                    jsonObject.put("grade", expertCertificate.getGrade());
                }

                if (expertBase.getIdCard().equals(leaderIdCard)) {
                    jsonObject.put("leader", true);
                } else {
                    jsonObject.put("leader", false);
                }
                jsonArray.add(jsonObject);
            }

            map.put("oldData", jsonArray.toString());

        }


        map.put("checkPlanId", checkPlanId);
        map.put("business", businessInfoServices.selectByBusinessCode(businessCode));
        return "jianYan/extractExpert/index";
    }


    @ResponseBody
    @RequestMapping(value = "automaticExtractionExpert", produces = "application/json;charset=UTF-8")
    public Object automaticExtractionExpert(String businessCode, Integer count, String affiliateCompany, String startTime, String endTime, String leaderGradeList) throws Exception {
        Map<String, Object> data = new HashMap();
        data.put("businessCode", businessCode);
//        data.put("count", count);
        data.put("leaderGradeList", leaderGradeList);
        data.put("affiliateCompany", affiliateCompany);
        data.put("startTime", startTime);
        data.put("endTime", endTime);
        String resultMessage = Properties.sendData(Properties.jianYanAutomaticExtractionExpert, data, Properties.uid, Properties.key);
        return ((Map) JsonUtil.json2Obj(resultMessage, Map.class)).get("data");

    }


    @ResponseBody
    @RequestMapping(value = "manuallyExtractionExpert", produces = "application/json;charset=UTF-8")
    public Object manuallyExtractionExpert(String name, String outLander, String businessCode, String affiliateCompany, Integer offset, Integer limit, String startTime, String endTime, String gradeList, String majorNumList) throws Exception {
        Map<String, Object> data = new HashMap();
        data.put("businessCode", businessCode);
        data.put("startTime", startTime);
        data.put("endTime", endTime);
        data.put("majorNumList", majorNumList);
        data.put("affiliateCompany", affiliateCompany);
        data.put("gradeList", gradeList);
        data.put("name", name);
        data.put("outLander", outLander);
        data.put("offset", offset);
        data.put("limit", limit);
        return ((Map) JsonUtil.json2Obj(Properties.sendData(Properties.jianYanManuallyExtractionExpert, data, Properties.uid, Properties.key), Map.class)).get("data");
    }


    @ResponseBody
    @RequestMapping(value = "getTreeByBusinessId", produces = "application/json;charset=UTF-8")
    public Object getTreeALLByBusinessPk(String businessId) throws Exception {

        BusinessInfo businessInfo = businessInfoServices.selectByPrimaryKey(businessId);
        List<MajorType> majorTypeList = majorTypeServices.selectMajorType(businessInfo.getItemId(), true);
        List<BusinessMajor> businessMajorList = businessMajorServices.selectByBusinessId(businessInfo.getId());
        JSONArray jsonArray = new JSONArray();

        for (MajorType majorType : majorTypeList) {
            majorType.setLive(ShortData.s0);
            for (BusinessMajor businessMajor : businessMajorList) {
                if (majorType.getNum().equals(businessMajor.getMajorNum())) {
                    majorType.setLive(ShortData.s1);
                    break;
                }
            }
            if (majorType.getLive() == 1) {
                jsonArray.add(ZTree.createZTreeJSONObject(majorType.getId(), majorType.getPid(), majorType.getName(), true, majorType.getNum()));
            } else {
                jsonArray.add(ZTree.createZTreeJSONObject(majorType.getId(), majorType.getPid(), majorType.getName(), false, majorType.getNum()));
            }
        }
        return jsonArray;

    }


    @ResponseBody
    @RequestMapping(value = "andExpertToWeiChuang", produces = "application/json;charset=UTF-8")
    public synchronized CommonResult andExpertToWeiChuang(String checkPlanId, String leaderIdCard, String crewIdCardList, Map map) throws Exception {

        CommonResult commonResult = new CommonResult();


        if (StringUtils.isBlank(leaderIdCard)) {
            commonResult.setCode(CommonResult.ZJ005);
            commonResult.setMessage("组长不能为空");
            return commonResult;
        }

        JyCheckPlan jyCheckPlan = jyCheckPlanServices.selectById(checkPlanId);
        if (jyCheckPlan == null) {
            commonResult.setCode(CommonResult.ZJ005);
            commonResult.setMessage("核查计划编号错误");
            return commonResult;
        }


        BusinessInfo businessInfo = businessInfoServices.selectByBusinessCode(jyCheckPlan.getAcceptedId());
        if (businessInfo == null) {
            commonResult.setCode(CommonResult.ZJ005);
            commonResult.setMessage("新专家系统无该业务。");
            return commonResult;
        } else {
            if (businessInfo.getInspectorCount() != null && businessInfo.getInspectorCount() > 0) {//新专家管理系统已经存在专家
                commonResult.setCode(CommonResult.ZJ005);
                commonResult.setMessage("专家组已经最终确认，无法再修改！");
                return commonResult;
            }
        }


        //删除以前记录
        jyExpertGroupServices.deleteByApplyId(checkPlanId);

        List<String> crewIdCardListTemp = new ArrayList<String>();//专家组集合
        crewIdCardListTemp.add(leaderIdCard);
        if (!StringUtils.isBlank(crewIdCardList)) {
            crewIdCardListTemp.addAll(Arrays.asList(crewIdCardList.split(",")));
        }

        //简单验证专家
        List<ExpertBase> expertBaseList = expertBaseServices.selectByIdCard(crewIdCardListTemp);
        if (expertBaseList.size() != crewIdCardListTemp.size()) {
            commonResult.setCode(CommonResult.ZJ005);
            commonResult.setMessage("存在无效的身份证号码");
            return commonResult;
        }

        List<JyExpertGroup> jyExpertGroupList = new ArrayList<JyExpertGroup>();

        for (int i = 0; i < expertBaseList.size(); i++) {
            ExpertBase expertBase = expertBaseList.get(i);
            JyExpertGroup jyExpertGroup = new JyExpertGroup();
            jyExpertGroupList.add(jyExpertGroup);


            UnitUser unitUser = unitUserServices.selectByIdCard(expertBase.getIdCard());
            if (unitUser == null) {
                commonResult.setCode(CommonResult.ZJ005);
                commonResult.setMessage("老专家库无该专家。" + expertBase.getIdCard());
                return commonResult;
            }


            //证书
            ExpertCertificate expertCertificate = expertCertificateServices.adminSelectByItemNum(expertBase.getId(), "35");
            if (expertCertificate == null) {
                commonResult.setCode(CommonResult.ZJ005);
                commonResult.setMessage("专家无证书。" + expertBase.getIdCard());
                return commonResult;
            } else {
                expertCertificate.setCertificateType(certificateTypeServices.selectByPrimaryKey(expertCertificate.getCertificateTypeId()));
                //证书编号
                jyExpertGroup.setWorkCert(expertCertificate.getNum());

                //EXPERT_TYPE 专家类别：ybdd_common_dic_expert_type_01 评审员 ；ybdd_common_dic_expert_type_02 特邀专家；ybdd_common_dic_expert_type_03 高级评审员
                String expertType = expertCertificate.getCertificateType().getName();
                if (expertType.equals("评审员")) {
                    jyExpertGroup.setExpertType("ybdd_common_dic_expert_type_01");
                } else if (expertType.equals("高级评审员")) {
                    jyExpertGroup.setExpertType("ybdd_common_dic_expert_type_03");
                } else {
                    jyExpertGroup.setExpertType("ybdd_common_dic_expert_type_02");
                }
            }

            jyExpertGroup.setId("expert" + IDFactory.getSnowflakeId());
            jyExpertGroup.setSourceId(unitUser.getPersonId());
            jyExpertGroup.setExpertId(unitUser.getUserId());//老专家系统的登录名
            jyExpertGroup.setApplyId(checkPlanId);
            jyExpertGroup.setItemId(checkPlanId);

            jyExpertGroup.setExpertName(expertBase.getName());//姓名
            jyExpertGroup.setIdCard(expertBase.getIdCard());//身份证号
            jyExpertGroup.setTel(expertBase.getPhone());  //电话号码
            jyExpertGroup.setEmail(expertBase.getEmail());  //email

            //工作单位
            ExpertCompany expertCompany = expertCompanyServices.adminSelectByExpertIdOnly(expertBase.getId());
            if (null != expertCompany) {
                //工作单位编号
                jyExpertGroup.setWorkUnitId(expertCompany.getCode());
                //工作单位名称
                jyExpertGroup.setWorkUnitName(expertCompany.getName());
            }

            // DUTY 组内职务：ybdd_common_dic_export_dute_01 组长；ybdd_common_dic_export_dute_02 组员
            if (expertBase.getIdCard().equals(leaderIdCard)) {
                jyExpertGroup.setDuty("ybdd_common_dic_export_dute_01");
            } else {
                jyExpertGroup.setDuty("ybdd_common_dic_export_dute_02");
            }


            //TITLE 职称：ybdd_common_dic_tech_title_0 教授级高工（研究员）；ybdd_common_dic_tech_title_1 高工（副教授）；ybdd_common_dic_tech_title_2 中级（工程师）；ybdd_common_dic_tech_title_3 初级 ； ybdd_common_dic_tech_title_4 其他；ybdd_common_dic_tech_title_5 无
//                   rank: {0: "正高", 1: "副高", 2: "中级", 3: "其他"},
            if (0 == expertBase.getRank()) {
                jyExpertGroup.setTitle("ybdd_common_dic_tech_title_0");

            } else if (1 == expertBase.getRank()) {
                jyExpertGroup.setTitle("ybdd_common_dic_tech_title_1");

            } else if (2 == expertBase.getRank()) {
                jyExpertGroup.setTitle("ybdd_common_dic_tech_title_2");

            } else if (3 == expertBase.getRank()) {
                jyExpertGroup.setTitle("ybdd_common_dic_tech_title_4");
            } else {
                jyExpertGroup.setTitle("ybdd_common_dic_tech_title_5");
            }

            //专业
            List<MajorType> majorTypeList = majorTypeServices.selectExpertMajorByLevel(expertBase.getId(), "369000000000004171", 1);
            StringBuffer a = new StringBuffer();
            for (MajorType majorType : majorTypeList) {
                a.append(majorType.getName());
                a.append("；");
            }
            jyExpertGroup.setSpeciality(a.substring(0, a.length() < 50 ? a.length() : 50));
        }
        jyExpertGroupServices.insertSelective(jyExpertGroupList);
        commonResult.setCode(CommonResult.ZJ001);
        commonResult.setMessage(CommonResult.ZJ001_M);
        return commonResult;

    }


}
